import 'dart:developer';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:kasax_demos2/providers/movie_provider.dart';

import 'entry/film_response.dart';
import 'film_item_widget.dart';
import 'item_placeholder_widget.dart';

/// 电影列表界面
class MovieListPage extends StatefulWidget {
  final String pageFlag;

  const MovieListPage(this.pageFlag, {Key? key}) : super(key: key);

  @override
  _MovieListPageState createState() => _MovieListPageState();
}

class _MovieListPageState extends State<MovieListPage> {
  // 每页数据条数
  static final int pageSize = 20;

  // 当前页数
  int currentPage = 1;

  // 总页数
  int totalPage = 0;

  // 小于5条就显示没有更多
  int dataSize = 0;

  // List<MovieNewInfoSubjects> dataList = <MovieNewInfoSubjects>[];
  List<Subjects> dataList = <Subjects>[];

  // 滚动监听,加载更多使用
  ScrollController _scrollController = ScrollController();

  late String loadMoreText;

  bool isLoading = true;

  @override
  void initState() {
    super.initState();

    _scrollController.addListener(() {
      log("scroll change");
      var maxScroll = _scrollController.position.maxScrollExtent;
      var pixel = _scrollController.position.pixels;
      log("scroll maxScroll: $maxScroll , pixel: $pixel");
      log("scroll currentPage: $currentPage , totalPage: $totalPage , dataSize :$dataSize");
      if (maxScroll == pixel &&
          currentPage < totalPage &&
          dataSize <= pageSize) {
        loadMoreText = "正在加载中。。。";
        loadMoreList();
      } else {
        loadMoreText = "没有更多数据。。。";
      }
    });

    _preload();
    _refresh();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: RefreshIndicator(
        onRefresh: _refresh,
        child: buildPageContent(),
      ),
    );
  }

  Widget buildPageContent() {
    log("buildPageContent...");
    log("dataList.len: ${dataList.length}");
    return Container(
      margin: EdgeInsets.only(left: 10, right: 10),
      child: ListView.separated(
        controller: _scrollController,
        itemBuilder: (context, index) {
          log("buildPageContent index: $index");
          // log("avatars: $avatars");
          return isLoading ? buildFilmPlaceholder() : buildFilmContent(index);
        },
        itemCount: dataList.length,
        separatorBuilder: (BuildContext context, int index) {
          return Divider();
        },
      ),
    );
  }

  Widget buildFilmContent(int index) {
    var info = dataList[index];
    return FilmItemWidget(info);
  }

  Future _refresh() async {
    log("下拉刷新");
    currentPage = 1;
    MovieProvider.getInstance()
        .fetchMovieList(widget.pageFlag, currentPage, pageSize)
        .then((value) {
      log("_refresh 数据回来了...");
      if (value != null) {
        dataList.clear();
        var list = value.subjects;
        totalPage = value.total!;
        if (list != null) {
          dataSize = list.length;
          isLoading = false;
          setState(() {
            if (list != null) {
              dataList.addAll(list);
            }
          });
        }
      } else {
        _preload();
      }
    });
  }

  void loadMoreList() {
    log("加载更多数据....");
    currentPage++;
    log("loadMoreList加载前: ${dataList.length}");
    MovieProvider.getInstance()
        .fetchMovieList(widget.pageFlag, currentPage, pageSize)
        .then((value) {
      var newDataLen = value.subjects!.length;
      dataSize = newDataLen;
      totalPage = value.total!;
      isLoading = false;
      log("loadMoreList 数据回来了... ,listSize: $newDataLen");
      if (newDataLen > 0) {
        setState(() {
          if (value.subjects != null) {
            dataList.addAll(value.subjects!);
            log("loadMoreList加载后: ${dataList.length}");
          }
        });
      }
    });
  }

  buildFilmPlaceholder() {
    return FilmItemPlaceholderWidget();
  }

  void _preload() {
    isLoading = true;
    setState(() {
      dataList = List.generate(10, (index) => Subjects());
      print("dataSize: ${dataList.length}");
    });
  }
}
